package com.zm.zmgz.service;

import com.zm.zmgz.dao.SalarySettlementBeanMapper;
import com.zm.zmgz.pojo.*;
import com.zm.zmgz.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: cjw
 * @Date: 2020/03/25/10:36
 * @Description:
 */
@Service
public class SalarySettlementService {

    @Autowired
    UserService userService;

    @Autowired
    SalarySettlementBeanMapper salarySettlementBeanMapper;

    @Autowired
    SalarySettlementDetailsService salarySettlementDetailsService;

    /**
     * @Description: 新增一个批次，赋值创建时间，创建用户,状态（解封）,最后编辑人和时间，并获取自增的主键值。
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-03-25 10:57:11
     */
    @Transactional
    public SalarySettlementBean addBatch(String identificationNumber, Date month) {
        // 获取用户名
        String userName = userService.getUserNameByidentificationNumber(identificationNumber);
        if (userName == null) {
            return null;
        }
        // 添加一个批次
        SalarySettlementBean salarySettlementBean = new SalarySettlementBean();
        salarySettlementBeanMapper.addBatch(salarySettlementBean);
        System.out.println("新增批次的id:" + salarySettlementBean.getId());
        salarySettlementBean.setCreatedate(new Date());
        salarySettlementBean.setCreateuser(userName);
        salarySettlementBean.setStatus("解封");
        salarySettlementBean.setEndeditdate(new Date());
        salarySettlementBean.setEndedituser(userName);
        salarySettlementBean.setBatch(month);
        // 更新新创建的批次
        int i = salarySettlementBeanMapper.updateByPrimaryKey(salarySettlementBean);
        System.out.println("新建的批次:" + salarySettlementBean);
        return salarySettlementBean;
    }

    /***
     * @Description: 获取离该时间最近创建的批次数据
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-03-26 21:35:32
     */
    public SalarySettlementBean getRecentRecords(Date createdate) { // 获取最新创建的记录
        SalarySettlementBeanExample salarySettlementBeanExample = new SalarySettlementBeanExample();
        SalarySettlementBeanExample.Criteria criteria = salarySettlementBeanExample.createCriteria();
        criteria.andCreatedateLessThan(createdate);
        salarySettlementBeanExample.setOrderByClause("createDate desc");
        List<SalarySettlementBean> salarySettlementBeans = salarySettlementBeanMapper.selectByExample(salarySettlementBeanExample);
        if (salarySettlementBeans.size() > 1) {
            System.out.println("最近创建的批次:" + salarySettlementBeans.get(1));
            return salarySettlementBeans.get(1);
        } else {
            System.out.println("暂无比" + createdate + "创建时间更早的批次!");
            return null;
        }
    }

    /***
     * @Description: 根据id获取SalarySettlementBean对象
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-03-25 17:38:51
     */
    public SalarySettlementBean getSalarySettlementById(String id) {
        SalarySettlementBean salarySettlementBean = salarySettlementBeanMapper.selectByPrimaryKey(Integer.parseInt(id));
        if (!Objects.isNull(salarySettlementBean)) {
            System.out.println(id + "批次:" + salarySettlementBean);
            return salarySettlementBean;
        } else {
            System.out.println("暂无" + id + "批次!");
            return null;
        }
    }

    /***
     * @Description: 获取最新批次数据
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-03-25 21:40:11
     */
    public SalarySettlementBean getNewestSalarySettlement() {
        SalarySettlementBeanExample salarySettlementBeanExample = new SalarySettlementBeanExample();
        salarySettlementBeanExample.setOrderByClause("id desc");
        List<SalarySettlementBean> salarySettlementBeanList = salarySettlementBeanMapper.selectByExample(salarySettlementBeanExample);
        if (!Objects.isNull(salarySettlementBeanList) && salarySettlementBeanList.size() > 0) {
            System.out.println("最新批次信息:" + salarySettlementBeanList.get(0));
            return salarySettlementBeanList.get(0);
        } else {
            System.out.println("暂无批次数据!");
            return null;
        }
    }


    /***
     * @Description: 根据id获取批次信息和批次明细信息, 拼接出table tag字符串并返回
     * 模板: 2020年3月工资结算表 创建日期:2020年3月24日(王力宏) 最后编辑:2020年3月24日(胡歌) 未发放
     * 模板: 2020年3月工资结算表(3) 创建日期:2020年3月24日(王力宏) 最后编辑:2020年3月24日(胡歌) 未发放
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-03-25 22:12:17
     */
    public String getTableTagById(String id) {
        // 2020年3月工资结算表
        String tableTag = "";
        SalarySettlementBean salarySettlementBean = null;
        if (Objects.isNull(id)) {
            salarySettlementBean = this.getNewestSalarySettlement();
        } else {
            salarySettlementBean = this.getSalarySettlementById(id);
        }
        if (Objects.isNull(salarySettlementBean)) {
            return "暂无批次数据！";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月");
        Date createdate = salarySettlementBean.getBatch();
        String format = simpleDateFormat.format(createdate);
        tableTag += format;
        tableTag += "工资结算表";

        // 2020年3月工资结算表(3)
        Date startTime = DateUtils.getMonthStart(salarySettlementBean.getBatch());
        Date endTime = DateUtils.getMonthEnd(salarySettlementBean.getBatch());
        List<SalarySettlementBean> salarySettlementBeanList = getSalarySettlementListByTimeLimit(startTime, endTime);
        if (!Objects.isNull(salarySettlementBeanList) && salarySettlementBeanList.size() > 0) {
            int index = 1;
            for (SalarySettlementBean settlementBean2 : salarySettlementBeanList) {
                if (settlementBean2.getId() == salarySettlementBean.getId()) {
                    break;
                }
                index++;
            }
            tableTag += "(" + index + ") ";
        } else {
            tableTag += " ";
        }

        // 2020年3月工资结算表 创建日期:2020年3月24日(王力宏) 最后编辑:2020年3月24日(胡歌)
        tableTag += "创建日期:" + DateUtils.getDateString(salarySettlementBean.getCreatedate(), DateUtils.DATEFORMAT2) + "(" + salarySettlementBean.getCreateuser() + ") 最后编辑:" + DateUtils.getDateString(salarySettlementBean.getCreatedate(), DateUtils.DATEFORMAT2) + "(" + salarySettlementBean.getCreateuser() + ") ";
        tableTag += salarySettlementDetailsService.getDistributionSituationByBatchId(salarySettlementBean.getId());
        System.out.println("第" + salarySettlementBean.getId() + "批次Tag：" + tableTag);
        return tableTag;
    }

    /***
     * @Description: 根据传入的时间范围(创建时间), 安装创建时间升序排序, 返回List<SalarySettlementBean>
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-03-26 07:34:03
     */
    public List<SalarySettlementBean> getSalarySettlementListByTimeLimit(Date startTime, Date endTime) {
        SalarySettlementBeanExample salarySettlementBeanExample = new SalarySettlementBeanExample();
        SalarySettlementBeanExample.Criteria criteria = salarySettlementBeanExample.createCriteria();
        criteria.andCreatedateBetween(startTime, endTime);
        salarySettlementBeanExample.setOrderByClause("createDate asc");
        List<SalarySettlementBean> salarySettlementBeanList = salarySettlementBeanMapper.selectByExample(salarySettlementBeanExample);
        if (salarySettlementBeanList.size() > 0) {
            System.out.println(DateUtils.getDateString(startTime, DateUtils.DATEFORMAT) + "至" + DateUtils.getDateString(endTime, DateUtils.DATEFORMAT) + "时间范围为:" + "共有" + salarySettlementBeanList.size() + "批次!");
            return salarySettlementBeanList;
        } else {
            System.out.println(DateUtils.getDateString(startTime, DateUtils.DATEFORMAT) + "至" + DateUtils.getDateString(endTime, DateUtils.DATEFORMAT) + "时间范围为:" + "没有批次!");
            return null;
        }
    }


    /***
     * @Description: 寻找年
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-03-31 13:50:37
     */
    public BatchOptionsBean getBatchOptionsBean(List<BatchOptionsBean> batchOptionsBeans, String label) {
        if (Objects.isNull(batchOptionsBeans)) {
            return null;
        }
        for (BatchOptionsBean batchOptionsBean : batchOptionsBeans) {
            if (label.equals(batchOptionsBean.getLabel())) {
                return batchOptionsBean;
            }
        }
        return null;
    }

    /***
     * @Description: 获取批次信息
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-03-31 13:13:58
     */
    public List<BatchOptionsBean> getBatchOptions() {
        SalarySettlementBeanExample salarySettlementBeanExample = new SalarySettlementBeanExample();
        salarySettlementBeanExample.setOrderByClause("batch asc");
        List<SalarySettlementBean> salarySettlementBeanList = salarySettlementBeanMapper.selectByExample(salarySettlementBeanExample);
        List<BatchOptionsBean> batchOptionsBeans = new ArrayList<>();
        for (SalarySettlementBean salarySettlementBean : salarySettlementBeanList) {
            Date createdate = salarySettlementBean.getBatch();
            String year = DateUtils.getDateString(createdate, "yyyy年");
            String month = DateUtils.getDateString(createdate, "M月");
            String dateString = DateUtils.getDateString(createdate, "d日");
            String patchLabel = "";
            Integer id = salarySettlementBean.getId();
            // 寻找年
            BatchOptionsBean batchOptionsBean = getBatchOptionsBean(batchOptionsBeans, year);
            if (Objects.isNull(batchOptionsBean)) { // 年为空,添加年
                BatchOptionsBean yearBatchOptionsBean1 = new BatchOptionsBean();
                yearBatchOptionsBean1.setLabel(year);
                batchOptionsBean = yearBatchOptionsBean1;
                batchOptionsBeans.add(batchOptionsBean);
            }
            // 获取月
            BatchOptionsBean batchOptionsBean1 = getBatchOptionsBean(batchOptionsBean.getChildren(), month);
            if (Objects.isNull(batchOptionsBean1)) { // 月为空,添加月
                BatchOptionsBean monthBatchOptionsBean1 = new BatchOptionsBean();
                monthBatchOptionsBean1.setLabel(month);
                batchOptionsBean1 = monthBatchOptionsBean1;
                List<BatchOptionsBean> children = batchOptionsBean.getChildren();
                if (Objects.isNull(children)) { // 年的孩子为空
                    ArrayList<BatchOptionsBean> batchOptionsBeans1 = new ArrayList<>();
                    batchOptionsBean.setChildren(batchOptionsBeans1);
                    children = batchOptionsBean.getChildren();
                }
                children.add(batchOptionsBean1);
            }
            // 赋值批次
            BatchOptionsBean batchOptionsBean2 = null;
            if (Objects.isNull(batchOptionsBean1.getChildren())) { // 此月还没有批次
                batchOptionsBean2 = new BatchOptionsBean();
                batchOptionsBean2.setLabel("第1批(" + dateString + ")");
                batchOptionsBean2.setValue(id + "");

            } else {
                int i = batchOptionsBean1.getChildren().size() + 1;
                batchOptionsBean2 = new BatchOptionsBean();
                batchOptionsBean2.setLabel("第" + i + "批(" + dateString + ")");
                batchOptionsBean2.setValue(id + "");
            }
            // 添加批次
            List<BatchOptionsBean> children = batchOptionsBean1.getChildren();
            if (Objects.isNull(children)) { // 月的孩子集为空,添加孩子集
                ArrayList<BatchOptionsBean> batchOptionsBeans1 = new ArrayList<>();
                batchOptionsBean1.setChildren(batchOptionsBeans1);
                children = batchOptionsBean1.getChildren();
            }
            children.add(batchOptionsBean2);
        }
        System.out.println("############################################");
        System.out.println("获取批次:" + salarySettlementBeanList);
        System.out.println("获取批次信息:" + batchOptionsBeans);
        return batchOptionsBeans;
    }

    /***
     * @Description: 删除指定批次和该批次的所有批次明细
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-03-31 17:38:30
     */
    @Transactional
    public int handleBatchDelete(int id) {
        int i = salarySettlementDetailsService.deleteByBatch(id);
        return salarySettlementBeanMapper.deleteByPrimaryKey(id);
    }


    /***
     * @Description: 把该批次状态取反
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-04-01 18:38:57
     */
    public int handleBatchStatusChange(Integer id) {

        SalarySettlementBean salarySettlementBean = salarySettlementBeanMapper.selectByPrimaryKey(id);
        String status = salarySettlementBean.getStatus();
        if (status.equals("冻结")) {
            salarySettlementBean.setStatus("解封");
        } else {
            salarySettlementBean.setStatus("冻结");
        }
        return salarySettlementBeanMapper.updateByPrimaryKey(salarySettlementBean);
    }

    /***
     * @Description: 日期+发放状态获取工资结算对象集合
     * 通过批次在工资结算表中获取批次id集合
     * 遍历该集合从工资结算明细表中获取记录集合并添加到总记录中并返回总记录集合
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-13 13:19:37
     */
    public List<SalarySettlementDetailsBean> getSalarySettlementListByTimeLimitAndStatus(Date date, String status) {
        // 通过批次在工资结算表中获取批次id集合
        List<Integer> list = getBatchIdsByDate(date);
        // 根据批次id从工资结算明细表中获取记录
        if (Objects.isNull(list) || list.size() == 0)
            return null;
        List<SalarySettlementDetailsBean> list1 = new ArrayList<>();
        for (Integer integer : list) {
            // 通过批次id和状态获取详细记录
            List<SalarySettlementDetailsBean> list2 = salarySettlementDetailsService.getSalarySettlementDetailsBeanByBatchIdAndstatus(integer,status);
            if(!Objects.isNull(list2) && list2.size() > 0)
                list1.addAll(list2);
        }
        return list1;
    }

    /***
     * @Description: 通过批次在工资结算表中获取批次id集合
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-21 18:29:00
     */
    private List<Integer> getBatchIdsByDate(Date date) {
        SalarySettlementBeanExample salarySettlementBeanExample = new SalarySettlementBeanExample();
        SalarySettlementBeanExample.Criteria criteria = salarySettlementBeanExample.createCriteria();
        Date monthStart = DateUtils.getMonthStart(date);
        Date monthEnd = DateUtils.getMonthEnd(date);
        criteria.andBatchBetween(monthStart,monthEnd);
        List<SalarySettlementBean> salarySettlementBeanList = salarySettlementBeanMapper.selectByExample(salarySettlementBeanExample);
        if (Objects.isNull(salarySettlementBeanList) || salarySettlementBeanList.size() == 0)
            return null;
        List<Integer> list = new ArrayList<>();
        for (SalarySettlementBean salarySettlementBean : salarySettlementBeanList) {
            list.add(salarySettlementBean.getId());
        }
        return list;
    }


}
